package com.my.listener;

import java.util.Enumeration;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

public class SessionDestoryedListener implements HttpSessionListener
{

	@Override
	public void sessionCreated(HttpSessionEvent event) {
		//event.getSession().setMaxInactiveInterval(-1);
		System.out.println("session 创建拉！ " + event.getSession().getId());
	}

	@Override
	@SuppressWarnings("unchecked")
	public void sessionDestroyed(HttpSessionEvent event) {
		System.out.println("session 销毁啦！ " + event.getSession().getId());
		ServletContext application = event.getSession().getServletContext();
		Enumeration<String> keys = application.getAttributeNames();
		while (keys.hasMoreElements()) {
			String k = keys.nextElement();
			Object o = application.getAttribute(k);
			if (o != null && o instanceof Map) {
				Map<String, Object> users = (Map<String, Object>) o;
				users.remove(event.getSession().getId());
				if (users.size() == 0) {
					application.removeAttribute(k);
					System.out.println("最后一个访问" + k + "方法的人也走了，Application 移除" + k);
				} else
					application.setAttribute(k, users);
				System.out.println("访问【" + k + "】方法的【" + event.getSession().getId() + "】被移除啦！");
			}
		}
	}

}
